#encoding:utf-8
import urllib2, cookielib
import urllib
import ocrmain
import re
def get_student_infomation(student_id,password):
	#cookie配置
	cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
	opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)

	#取得随机token
	try:
		url_index=r'https://portal.hnust.edu.cn:8443/cas/login'
		content=opener.open(url_index).read()
		f=content.find('lt')
		token=content[f+11:f+87]
		# print token
	except:
		print student_id,'get token error'
		return ''

	#获取验证码
	try:
		temp_file_name='temp.jpg'
		url_code=r'https://portal.hnust.edu.cn:8443/cas/security/initDigitPicture.do?Rgb=255|255|255&width=200&height=500'
		content = opener.open(url_code).read()
		open(temp_file_name,'wb').write(content)
		word=ocrmain.getword(temp_file_name)
		# print 'ocrresult=',word
	except :
		print student_id,'code error'
		return get_student_infomation(student_id,password)
	if len(word)!=4:
		print student_id,'code error word'
		return get_student_infomation(student_id,password)
	
	#登录
	try:
		url_login_page=r'https://portal.hnust.edu.cn:8443/cas/login?service=http%3A%2F%2Fportal.hnust.edu.cn%2FP%2Findex.jsp'
		postdata=urllib.urlencode({
		    'username':str(student_id),
		    'password':password,
		    'j_digitPicture':word,#验证码
		    '_eventId':'submit',
		    'loginType':'0',
		    'lt':token
		})
		content=opener.open(url_login_page,postdata).read()
	except:
		print student_id,'login error'
		return get_student_infomation(student_id,password)

	if content.find('success')==-1:
		if content.find('您输入的验证码有误')!=-1:
			return get_student_infomation(student_id, password)
		print student_id,'密码错误'
		return 'error'
	#login success
	print opener.open("http://portal.hnust.edu.cn/P/appmanager/s/MyDesktop").read()

	try:
		#退出登录
		url_index=r'https://portal.hnust.edu.cn:8443/cas/logout'
		content=opener.open(url_index).read()
	except:
		print student_id,'logout error'
	return 'ok'

get_student_infomation(1205010207,"")

